import cMenuDialogHTML from './rightmenu.html'


import $ from "jquery";
const $click = (element, handler) => {
  element.addEventListener('mousedown', handler)
  // element.addEventListener('click', handler)
  element.addEventListener('touchend', handler)
}
/**
 * @class RightMenu
 */
export class RightMenu extends HTMLElement {
  /**
    * @function constructor
    */
  constructor(svgShow, menuList, menuId, i18next, showType) {
    super()

    this.svgShow = svgShow

    this.showType = showType

    this.lockMap = new Map()

    this.buts = []
    // create the shadowDom and insert the template
    const template = document.createElement('template')
    template.innerHTML = cMenuDialogHTML
    var str = `<ul id="${menuId}" class="contextMenu">`
    if (!menuList) return
    for (var i = 0; i < menuList.length; i++) {
      if (menuList[i].children) {
        str += `<li class="lichild ${menuList[i].class ? menuList[i].class : ''}"><a href="#${menuList[i].id}" id="${menuList[i].id}">${i18next.t(menuList[i].id.replace("-", "."))}</a><ul>`
        this.buts.push(menuList[i].id)
        for (var j = 0; j < menuList[i].children.length; j++) {
          var opType = menuList[i].children[j].opType
          opType = opType ? `opType="${opType}"` : ""
          str += `<li><a href="#${menuList[i].children[j].id}" ${opType} id="${menuList[i].children[j].id}">${i18next.t(menuList[i].children[j].id.replace("-", "."))}</a></li>`
          this.buts.push(menuList[i].children[j].id)
        }
        str += `</ul></li>`
      } else {
        var opType = menuList[i].opType
        opType = opType ? `opType="${opType}"` : ""
        str += `<li class="${menuList[i].class ? menuList[i].class : ''}"><a href="#${menuList[i].id}" ${opType}  id="${menuList[i].id}">${i18next.t(menuList[i].id.replace("-", "."))}</a></li>`
        this.buts.push(menuList[i].id)
      }
    }
    str += '</ul>'
    template.innerHTML += str
    this._shadowRoot = this.attachShadow({ mode: 'open' })
    this._shadowRoot.append(template.content.cloneNode(true))
    this._svg = document.getElementById('svg')
    this.$dialog = this._shadowRoot.querySelector(`#${menuId}`)


  }

  /**
   * @function init
   * @param {any} name
   * @returns {void}
   */
  init(i18next) {
  }

  /**
   * @function observedAttributes
   * @returns {any} observed
   */
  static get observedAttributes() {
    return ['disableallmenu', 'enablemenuitems', 'disablemenuitems', 'tools-cut',
      'tools-copy', 'tools-paste', 'tools-paste_in_place', 'tools-delete', 'tools-group',
      'tools-ungroup', 'tools-move_front', 'tools-move_up', 'tools-move_down',
      'tools-move_back']
  }

  /**
   * @function attributeChangedCallback
   * @param {string} name
   * @param {string} oldValue
   * @param {string} newValue
   * @returns {void}
   */
  attributeChangedCallback(name, oldValue, newValue) {

  }

  /**
   * @function get
   * @returns {any}
   */
  get disableallmenu() {
    return this.getAttribute('disableallmenu')
  }

  /**
   * @function set
   * @returns {void}
   */
  set disableallmenu(value) {
    this.setAttribute('disableallmenu', value)
  }

  /**
   * @function get
   * @returns {any}
   */
  get enablemenuitems() {
    return this.getAttribute('enablemenuitems')
  }

  /**
   * @function set
   * @returns {void}
   */
  set enablemenuitems(value) {
    this.setAttribute('enablemenuitems', value)
  }

  /**
   * @function get
   * @returns {any}
   */
  get disablemenuitems() {
    return this.getAttribute('disablemenuitems')
  }

  /**
   * @function set
   * @returns {void}
   */
  set disablemenuitems(value) {
    this.setAttribute('disablemenuitems', value)
  }

  /**
   * @function connectedCallback
   * @returns {void}
   */
  connectedCallback() {
    const current = this

    const findEms = (elem) => {
      if (elem.getAttribute("doc-type") && elem.getAttribute("data") && elem.getAttribute("doc-type") != "text") {
        return elem
      } else {
        if (elem.parentElement) {
          return findEms(elem.parentElement)
        } else {
          return null
        }
      }
    }

    const onMenuOpenHandler = (e) => {
      e.preventDefault()
      var emsElem = findEms(e.target)
      if (emsElem == null) {
        if (this.showType == 'normal') {
          this.svgShow.menuBindingElem = null
        } else {
          return
        }
      } else {
        if (this.showType.indexOf(emsElem.getAttribute("doc-type")) > -1) {
          this.svgShow.menuBindingElem = emsElem
        } else if (this.showType == 'normal') {
          this.svgShow.menuBindingElem = null
        } else {
          return
        }
      }
      // Detect mouse position
      let x = e.pageX
      let y = e.pageY

      const xOff = screen.width - 250 // menu width
      const yOff = screen.height - (276 + 150) // menu height + bottom panel height and scroll bar

      if (x > xOff) {
        x = xOff
      }
      if (y > yOff) {
        y = yOff
      }
      current.$dialog.style.top = y + 'px'
      current.$dialog.style.left = x + 'px'
      current.$dialog.style.display = 'block'

      if (this.svgShow.currentRightMenu && this.svgShow.currentRightMenu.id != current.$dialog.id) {
        this.svgShow.currentRightMenu.style.display = 'none'
      }
      if (this.showType == "KG_DZ_DD") {
        var objLock = this.svgShow.lockMap.get(this.svgShow.menuBindingElem.id)
        console.log(objLock)
        // var canYk = this.svgShow.allSvgElemOpts.get(this.svgShow.menuBindingElem.id).data.startsWith("2:")
        // if (canYk && (objLock == false || (objLock == null && !this.svgShow.isAllLock))) {
        //   $(current.$dialog).find("#svg-yk").parent("li").removeClass("sock")
        // } else {
        //   $(current.$dialog).find("#svg-yk").parent("li").addClass("sock")

        // }


        if (objLock) {

         
            if (objLock.yaokongBlock=='yaokongBlock_true') {
              $(current.$dialog).find("#svg-closeyk").parent("li").addClass("haSock")
              $(current.$dialog).find("#svg-openyk").parent("li").removeClass("haSock")
              $(current.$dialog).find("#svg-yk").parent("li").addClass("sock")
             

            } else if(objLock.yaokongBlock=='yaokongBlock_false') {
              $(current.$dialog).find("#svg-openyk").parent("li").addClass("haSock")
              $(current.$dialog).find("#svg-closeyk").parent("li").removeClass("haSock")
              $(current.$dialog).find("#svg-yk").parent("li").removeClass("sock")
            }
          



         

          



          if (objLock.yaoxinBlockHe=='yaoxinBlockHe_true') {
            $(current.$dialog).find("#svg-closeyxH").parent("li").addClass("haSock")
            $(current.$dialog).find("#svg-closeyxF").parent("li").removeClass("haSock")

          } else if(objLock.yaoxinBlockHe=='yaoxinBlockHe_false') {
            $(current.$dialog).find("#svg-closeyxF").parent("li").addClass("haSock")
            $(current.$dialog).find("#svg-closeyxH").parent("li").removeClass("haSock")
          }


          if (objLock.yaoxinUnBlock=="yaoxinUnBlock_true") {
            $(current.$dialog).find("#svg-openyx").parent("li").addClass("haSock")
            $(current.$dialog).find("#svg-closeyxH").parent("li").removeClass("haSock")
            $(current.$dialog).find("#svg-closeyxF").parent("li").removeClass("haSock")
          } else if("yaoxinUnBlock_false") {
            $(current.$dialog).find("#svg-openyx").parent("li").removeClass("haSock")
          }


        }



        if (this.showType == "normal") {
          if (this.svgShow.isAllLock) {
            $(current.$dialog).find("#svg-closeyk").parent("li").addClass("haSock")
            $(current.$dialog).find("#svg-openyk").parent("li").removeClass("haSock")


          } else {
            $(current.$dialog).find("#svg-openyk").parent("li").addClass("haSock")
            $(current.$dialog).find("#svg-closeyk").parent("li").removeClass("haSock")

          }



        }

      }




      this.svgShow.currentRightMenu = current.$dialog
    }
    const onMenuCloseHandler = (e) => {
      if (e.button !== 2) {
        if (this.currentMenuitem && e.target.tagName != "svg") return
        current.$dialog.style.display = 'none'
      }
    }
    const onMenuClickHandler = (e) => {
      // var menuId = $(e.target).parent().parent().attr("id")
      console.log(this.showType, "我这边看下模式")
      if (this.showType == "normal") {
        if ($(e.target).is("#svg-openyk")) {
          this.svgShow.isAllLock = false
          // this.svgShow.lockMap = new Map()
        }
        if ($(e.target).is("#svg-closeyk")) {
          this.svgShow.isAllLock = true;
          // this.svgShow.lockMap = new Map()
        }
      } else if (this.showType == "KG_DZ_DD") {

        if (this.svgShow.lockMap.get(this.svgShow.menuBindingElem.id)) {
          let { yaokongBlock, yaoxinBlockHe, yaoxinUnBlock } = this.svgShow.lockMap.get(this.svgShow.menuBindingElem.id);
          var obj = {
            yaokongBlock,
            yaoxinBlockHe,
            yaoxinUnBlock
          }
        } else {
          var obj = {
            yaokongBlock: "",
            yaoxinBlockHe: "",
            yaoxinUnBlock: "",
          }

        }


        if ($(e.target).is("#svg-openyk")) {
          obj.yaokongBlock = "yaokongBlock_false";
          this.svgShow.lockMap.set(this.svgShow.menuBindingElem.id, obj)
        }
        if ($(e.target).is("#svg-closeyk")) {
          obj.yaokongBlock = "yaokongBlock_true";
          this.svgShow.lockMap.set(this.svgShow.menuBindingElem.id, obj)
        }





        if ($(e.target).is("#svg-closeyxH")) {
          obj.yaoxinBlockHe = "yaoxinBlockHe_true";
          obj.yaoxinUnBlock = "yaoxinUnBlock_false";
          this.svgShow.lockMap.set(this.svgShow.menuBindingElem.id, obj)
        }
        if ($(e.target).is("#svg-closeyxF")) {
          obj.yaoxinBlockHe = "yaoxinBlockHe_false";
          obj.yaoxinUnBlock = "yaoxinUnBlock_false";
          this.svgShow.lockMap.set(this.svgShow.menuBindingElem.id, obj)
        }


        if ($(e.target).is("#svg-openyx")) {
          obj.yaoxinUnBlock = "yaoxinUnBlock_true";
          this.svgShow.lockMap.set(this.svgShow.menuBindingElem.id, obj)
        }



        // if($(e.target).is("#svg-openyk")){
        //   this.svgShow.lockMap.set(this.svgShow.menuBindingElem.id,false)
        // }
        // if($(e.target).is("#svg-closeyk")){
        //   this.svgShow.lockMap.set(this.svgShow.menuBindingElem.id,true)
        // }
      }

      if (e.target.parentElement.classList.contains("lichild")) {
        this.currentMenuitem = e.target.parentElement
        return
      }
      this.currentMenuitem = null
      const triggerEvent = new CustomEvent('change' + this.showType, {
        detail: {
          trigger: e.target.getAttribute("href"),
          opType: e.target.getAttribute("opType"),
        }
      })
      this.dispatchEvent(triggerEvent)
    }

    this._svg.addEventListener('contextmenu', onMenuOpenHandler)
    for (var i = 0; i < this.buts.length; i++) {
      $click(this._shadowRoot.querySelector("#" + this.buts[i]), (evt) => onMenuClickHandler(evt))
    }
    this._svg.addEventListener('mouseup', onMenuCloseHandler)
  }
}

// Register
customElements.define('right-menu-dialog', RightMenu)